package com.rr.middle;

import com.rr.entity.ListNode;

public class RemoveNthFromEnd {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode end = head;
        ListNode middle = head;
        ListNode pre = null;
        ListNode next = middle.next;
        for (int i = 0; i < n; i++) {
            end = end.next;
        }
        while (end != null) {
            end = end.next;
            pre = middle;
            middle = middle.next;
            next = middle.next;
        }
        if (pre != null) {
            pre.next = next;
        } else {
            return head.next;
        }
        return head;
    }

    public static void main(String[] args) {
        RemoveNthFromEnd removeNthFromEnd = new RemoveNthFromEnd();
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(2);
        ListNode n3 = new ListNode(3);
        ListNode n4 = new ListNode(4);
        ListNode n5 = new ListNode(5);
//        n1.next = n2;
//        n2.next = n3;
//        n3.next = n4;
//        n4.next = n5;
        removeNthFromEnd.removeNthFromEnd(n1, 1);
    }
}
